package wall

import (
	"encoding/binary"
	"fmt"
	"net"

	"gitee.com/haodreams/libs/sock"
)

//发送文件不合并

type Writer struct {
	ackChar   byte   //确认字符
	timeoutMs int64  //超时时间,单位毫秒
	head      []byte //包头2字节
	withWall  bool   //是否开启隔离
	conn      *net.TCPConn
}

func (m *Writer) SetAckChar(ackChar byte) *Writer {
	m.ackChar = ackChar
	m.withWall = true
	return m
}

func (m *Writer) SetTimeout(timeoutMs int64) *Writer {
	m.timeoutMs = min(max(timeoutMs, 1000), 120*1000)
	return m
}

func (m *Writer) SetConn(conn *net.TCPConn) *Writer {
	m.conn = conn
	return m
}

func (m *Writer) Setup() (err error) {
	//初始化包头
	m.head = make([]byte, 2)
	return nil
}

func (m *Writer) Write(buf []byte) (n int, err error) {
	if len(buf) > 64*1024 {
		err = fmt.Errorf("数据长度不能超过64k")
		return
	}

	//写入数据长度
	binary.BigEndian.PutUint16(m.head, uint16(len(buf)))
	n, err = m.conn.Write(m.head)
	if err != nil {
		return
	}

	//写入数据
	n, err = m.conn.Write(buf)
	if err != nil {
		return
	}

	if m.withWall {
		_, err := sock.ReadTimeoutMs(m.conn, m.head[:1], int(m.timeoutMs))
		if err != nil {
			return n, err
		}
		if m.head[0] != m.ackChar {
			err = fmt.Errorf("确认字符错误")
			return n, err
		}
	}
	return
}
